package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"shuqi_novel/models"
	"time"

	"shuqi_novel/shop_rpc/internal/svc"
	"shuqi_novel/shop_rpc/shop_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type BookListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBookListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BookListLogic {
	return &BookListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BookListLogic) BookList(in *shop_rpc.BookListRequest) (*shop_rpc.BookListResponse, error) {
	// todo: add your logic here and delete this line

	var total int
	var data []*shop_rpc.Book
	key := fmt.Sprintf("user_id = %d;page = %d from books_list", in.AuthorId, in.Page)
	get, _ := models.RDB.Get(models.Ctx, key).Result()
	if get == "" {

		var books []struct {
			models.Book
			AuthorName string
		}

		if models.DB.Model(&models.Book{}).Joins("join users on books.author_id = users.id").Select("books.*,users.user_name as author_name").Where("author_id = ?", in.AuthorId).Limit(5).Offset(int(in.Page-1)*5).Find(&books).Error != nil {
			return nil, fmt.Errorf("服务器繁忙")
		}
		if models.DB.Where("author_id = ?", in.AuthorId).Model(&models.Book{}).Pluck("count(*)", &total).Error != nil {
			return nil, fmt.Errorf("服务器繁忙")
		}
		for _, book := range books {
			var get shop_rpc.Book
			get.Title = book.Title
			get.Type = book.Type
			get.Image = book.Image
			get.AuthorName = book.AuthorName
			data = append(data, &get)
		}
		set, _ := json.Marshal(&data)
		models.RDB.Set(models.Ctx, key, set, 12*time.Hour)
	} else {
		json.Unmarshal([]byte(get), &data)
	}
	return &shop_rpc.BookListResponse{
		Books: data,
		Total: int64(total),
	}, nil
}
